const connection = require("../config/mysql")

class MomentService {
    async create(content, userId) {
        const statement = "INSERT INTO `moment` (id,content,user_id) VALUES (REPLACE(UUID(),'-',''),?,?);";
        const [result] = await connection.execute(statement, [content, userId])
        return result
    }
    async queryLists(offset = 0, size = 5) {
        const statement = `SELECT m.id id, m.content content, m.createAt createTime, m.uploadAt updateTime,
JSON_OBJECT('id', u.id, 'name', u.name, 'createTime', u.createAt, 'updateTiem', u.updateAt) userInfo,
(SELECT COUNT(*) FROM comment WHERE comment.moment_id = m.id) commentCount FROM moment m 
LEFT JOIN user u ON u.id = m.user_id LIMIT ? OFFSET ?;`

        const [result] = await connection.execute(statement, [String(size), String(offset)])
        return result
    }

    async queryDetail(momentId) {
        const statement = `SELECT m.id id, m.content content, m.createAt createTiem, m.uploadAt uploadTiem,
                            JSON_OBJECT('id', u.id, 'name', u.name, u.createAt, 'updateTiem', u.updateAt) userInfo,
                            (
                                JSON_ARRAYAGG(JSON_OBJECT(
                                    'id', c.id, 'content', c.content, 'commentId', c.comment_id,
                                    'user', JSON_OBJECT('id', cu.id, 'name', cu.name)
                                ))
                            ) comments
                            FROM moment m
                            LEFT JOIN user u ON u.id = m.user_id
                            LEFT JOIN comment c ON c.comment_id = m.id
                            LEFT JOIN user cu ON cu.id = c.user_id
                            WHERE m.id = ?
                            GROUP BY m.id;`

        try {
            const [result] = await connection.execute(statement, [momentId])
            return result
        } catch (error) {
            console.log(error);
        }
    }

    async updateModify(content, momentId) {
        const statement = "UPDATE moment SET content = ? WHERE id = ?;"
        const [result] = await connection.execute(statement, [content, momentId])
        return result
    }

    async removeMoment(momentId) {
        const statement = "DELETE FROM moment WHERE id = ?;"
        const [result] = await connection.execute(statement, [momentId])
        return result
    }
}

module.exports = new MomentService()